﻿using FluentAssertions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using NewRetail.Application.Components.WechatOrAlipayPayment.Model;
using NewRetail.Application.Components.WechatOrAlipayPayment.Services;
using NewRetail.Application.Core;
using SKIT.FlurlHttpClient.Wechat.TenpayV3.Models;
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace NewRetail.Api.Controllers.WeChartControllers
{
    [NewRetailRoute("wechat-alipay-payment")]
    public class WeChatOrAlipayPaymentController : BaseController
    {
        #region Field
        public readonly IWeChatOrAlipayPaymentService _weChatOrAlipayPaymentService;
        private readonly ILogger _logger;
        #endregion

        #region Constructor
        public WeChatOrAlipayPaymentController(IWeChatOrAlipayPaymentService weChatOrAlipayPaymentService, ILogger<WeChatOrAlipayPaymentController> logger)
        {
            _weChatOrAlipayPaymentService = weChatOrAlipayPaymentService;
            _logger = logger;
        }
        #endregion

        #region method

        #region 支付宝相关

        #region 阿里网页支付
        /// <summary>
        /// 阿里网页支付
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [HttpPost("wap-alipay-pay")]
        public async Task<ResponseEntity<PayResultShowDto>> WapAlipayPay(AlipayTradeWapPayViewDto inputDto)
        {
            var ret = new ResponseEntity<PayResultShowDto>();
            try
            {
                var result = await _weChatOrAlipayPaymentService.WapAlipayPay(inputDto);
                if (result.Item1 == null)
                    ret.SetError("支付失败！" + result.Item3);
                ret.SetData(result.Item1);
            }
            catch (Exception e)
            {
                ret.SetError("发生内部错误！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 阿里支付回调通知
        /// <summary>
        /// 阿里支付回调通知
        /// </summary>
        /// <returns></returns>
        [HttpPost("alipay-notify")]
        public async Task<ResponseEntity<string>> AsynAlipayNotify()
        {
            var ret = new ResponseEntity<string>();
            try
            {
                var result = await _weChatOrAlipayPaymentService.AsynAlipayNotify(Request);
                if (result != null)
                    ret.SetError("支付失败！" + result);
                ret.SetData("Success");
            }
            catch (Exception e)
            {
                ret.SetError("发生内部错误！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #endregion

        #region 微信相关

        #region 微信JSAPI下单
        /// <summary>
        /// 微信JSAPI下单
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-createpaytransactionjsapi")]
        public async Task<ResponseEntity<WeChatPayTransactionJsapiShowDto>> CreatePayTransactionJsapi([FromBody] CreateOrderByJsapiRequestDto inputDto)
        {
            inputDto.Should().NotBeNull();
            var ret = new ResponseEntity<WeChatPayTransactionJsapiShowDto>();
            try
            {
                var result = await _weChatOrAlipayPaymentService.CreatePayTransactionJsapi(inputDto);
                if (string.IsNullOrEmpty(result.Item1))
                    ret.SetError("创建订单失败！" + result.Item2);
                else
                    ret.SetData(result.Item3);
            }
            catch (Exception e)
            {
                ret.SetError("创建订单失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 微信端商户订单号查询
        /// <summary>
        /// 微信端商户订单号查询
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-getwxpaytransactionbyouttradenumber")]
        public async Task<ResponseEntity<GetPayTransactionByOutTradeNumberResponse>> GetPayTransactionByOutTradeNumberAsync([FromBody] PayTransactionByOutTradeNumberRequestDto requestModel)
        {
            requestModel.Should().NotBeNull();
            var ret = new ResponseEntity<GetPayTransactionByOutTradeNumberResponse>();
            try
            {
                var result = await _weChatOrAlipayPaymentService.GetPayTransactionByOutTradeNumberAsync(requestModel);
                if (!string.IsNullOrEmpty(result.Item1))
                    ret.SetError("查询订单失败！" + result.Item1);
                else
                    ret.SetData(result.Item2);
            }
            catch (Exception e)
            {
                ret.SetError("查询订单失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 微信端商户关闭订单
        /// <summary>
        /// 微信端商户关闭订单
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>

        [HttpPost("wechat-closewxpaytransactionbyouttradenumber")]
        public async Task<ResponseEntity<ClosePayTransactionResponse>> ClosePayTransactionByOutTradeNumberAsync([FromBody] PayTransactionByOutTradeNumberRequestDto requestModel)
        {
            requestModel.Should().NotBeNull();
            var ret = new ResponseEntity<ClosePayTransactionResponse>();
            try
            {
                var result = await _weChatOrAlipayPaymentService.ClosePayTransactionByOutTradeNumberAsync(requestModel);
                if (!string.IsNullOrEmpty(result.Item1))
                    ret.SetError("关闭订单失败！" + result.Item1);
                else
                    ret.SetData(result.Item2);
            }
            catch (Exception e)
            {
                ret.SetError("关闭订单失败！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #region 微信支付回调通知(弃用)
        /// <summary>
        /// 微信支付回调通知
        /// </summary>
        /// <returns></returns>
        [HttpPost("wechat-notify")]
        public async Task<ResponseEntity<string>> AsynWechatNotify()
        {
            var ret = new ResponseEntity<string>();
            try
            {
                using var reader = new StreamReader(Request.Body, Encoding.UTF8);
                string content = await reader.ReadToEndAsync();
                var result = await _weChatOrAlipayPaymentService.AsynWechatNotify(content);
                if (result != null)
                    ret.SetError("支付失败！" + result);
                ret.SetData("Success");
            }
            catch (Exception e)
            {
                ret.SetError("发生内部错误！" + e.Message);
                _logger.LogError(e.Message);
            }

            return ret;
        }
        #endregion

        #endregion

        #endregion
    }
}
